package org.jsola.hr.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.jsola.admin.service.ISiteService;
import org.jsola.admin.vo.SiteListVO;
import org.jsola.hr.common.HrKit;
import org.jsola.hr.dao.IGregorianCalendarDAO;
import org.jsola.hr.entity.GregorianCalendarDO;
import org.jsola.hr.provider.ISiteProviderService;
import org.jsola.hr.query.GregorianCalendarQuery;
import org.jsola.hr.service.IGregorianCalendarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.ParseException;
import java.util.*;

/**
 * 初始化日历表
 *
 * @author wxz
 */
@Slf4j
@Component
public class CalendarTask {

    @Autowired
    private IGregorianCalendarDAO gregorianCalendarDAO;
    @Autowired
    private ISiteProviderService siteProviderService;
    @Autowired
    private IGregorianCalendarService gregorianCalendarService;

    /**
     * 每月最后一天23点执行一次
     */
    // @Scheduled(cron = "0 59 23 28-31 * ?") // 每月最后一天23点执行一次
    @Scheduled(cron = "30 10 4 * * ?") // 每天4点10分30秒触发
    public void initGregorianCalendar() {

        // 下个月
        Date nextMonth =  org.jsola.hr.common.DateUtils.getFirstDayOfNextMonth(DateFormatUtils.format(new Date(), "yyyy-MM-dd"));

        String yearly = DateFormatUtils.format(nextMonth, "yyyy");
        String monthly = DateFormatUtils.format(nextMonth, "MM");

        // 调用API接口获取当月的法定节假日
        String url = "http://tool.bitefu.net/jiari/?d=" + yearly + monthly;
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).method("GET",null).build();
        Call call = okHttpClient.newCall(request);
        String jsonData = "";
        try {
            Response response = call.execute();
            jsonData = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (StringUtils.isBlank(jsonData)) {
            return;
        }

        log.info("获取节假日信息---->" + jsonData);

        JSONObject object = JSON.parseObject(jsonData);
        Map<String, Integer> map = null;

        try {
            map = JSONObject.parseObject(object.get(yearly + monthly).toString(), Map.class);
        } catch (Exception e) {
            log.info("解析错误...");
        }


        // 查询所有站点
        List<SiteListVO> siteList = siteProviderService.select();
        if (siteList == null || siteList.size() <= 0) {
            log.info("未查询到站点信息");
            return;
        }

        // 获取某个月有多少天
        int days = HrKit.getDaysOfMonth(nextMonth);

        for (int i = 1; i <= days; i++) {

            String dayStr = "";
            if (i < 10) {
                dayStr = "0" + i;
            }
            else {
                dayStr = i + "";
            }
            String dateStr = yearly + "-" + monthly + "-" + dayStr;

            // 1-工作日,2-休息日,3-法定节假日
            int dateType = 1;

            if (map != null && map.size() > 0) {
                for(Map.Entry<String, Integer> entry : map.entrySet()) {

                    // 工作日对应结果为 0, 休息日对应结果为 1, 节假日对应的结果为 2
                    if (entry.getKey().equals(monthly + dayStr)) {

                        int type = entry.getValue();
                        if (type == 0) {
                            dateType = 1;
                        }
                        else if (type == 1) {
                            dateType = 2;
                        }
                        else if (type == 2) {
                            dateType = 3;
                        }
                    }
                }
            }

            for (SiteListVO site : siteList) {

                if (dateType == 1) {
                    continue;
                }

                // 查询这个站点下，是否已经有了某年，某月某日的数据了
                GregorianCalendarQuery gregorianCalendarQuery = new GregorianCalendarQuery();
                gregorianCalendarQuery.setDateStr(dateStr);
                List<GregorianCalendarDO> gregorianCalendarList = gregorianCalendarService.selectDO(gregorianCalendarQuery, site.getId());
                if (gregorianCalendarList.size() > 0) {
                    continue;
                }

                GregorianCalendarDO gregorianCalendarDO = new GregorianCalendarDO();

                gregorianCalendarDO.setId(UUID.randomUUID().toString().replace("-", ""));
                gregorianCalendarDO.setYearly(yearly);
                gregorianCalendarDO.setMonthly(monthly);
                gregorianCalendarDO.setDaily(dayStr);
                gregorianCalendarDO.setDateStr(dateStr);
                gregorianCalendarDO.setDateType(dateType);
                gregorianCalendarDO.setCompanyId("");
                gregorianCalendarDO.setGmtCreate(new Date());
                gregorianCalendarDO.setGmtModified(new Date());
                gregorianCalendarDO.setCreateUserId("task");
                gregorianCalendarDO.setModifiedUserId("task");
                gregorianCalendarDO.setSiteId(site.getId());
                gregorianCalendarDO.setValid(true);

                gregorianCalendarDAO.insert(gregorianCalendarDO);
            }

        }
    }

    public static void main(String[] args) {

        String yearly = "2020";
        String monthly = "01";

        String url = "http://tool.bitefu.net/jiari/?d=" + yearly + monthly;
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).method("GET",null).build();
        Call call = okHttpClient.newCall(request);
        String jsonData = "";
        try {
            Response response = call.execute();
            jsonData = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (StringUtils.isBlank(jsonData)) {
            return;
        }

        JSONObject object = JSON.parseObject(jsonData);
        Map map = JSONObject.parseObject(object.get(yearly + monthly).toString(), Map.class);

        System.out.println(JSON.toJSONString(map));
    }

}
